<template>
  <div class="layout-tabview">
    <a-tabs
      v-model:active-key="tabActive"
      hide-content
      editable
      type="rounded"
      @tab-click="handleTabClick"
      @delete="handleTabRemove"
    >
      <template #extra>
        <a-dropdown position="br" @select="handleCommand">
          <div class="layout-tabview--drop">
            <icon-arco type="icon-down" />
          </div>
          <template #content>
            <a-doption
              v-for="item in tabEventBtns"
              :key="item.key"
              :value="item.key"
              :disabled="item.disabled"
            >
              <template #icon><icon-arco :type="item.icon" :size="14" /></template>
              <span>{{ item.title }}</span>
            </a-doption>
          </template>
        </a-dropdown>
      </template>
      <template v-for="route in visitedRoutes" :key="route.path">
        <a-tab-pane
          v-if="route.path"
          :key="route.path"
          :title="route.title || route.meta?.title"
          :closable="!isAffix(route)"
        />
      </template>
    </a-tabs>
  </div>
</template>

<script setup>
import { reactive, toRefs, watch, computed, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTabviewStore } from '@/store/modules/tabview'

const props = defineProps({
  menuList: {
    type: Array,
    default: () => []
  }
})

// 菜单功能按钮
const tabEventBtns = reactive([
  { title: '刷新页面', key: 'refreshRoute', icon: 'icon-refresh', disabled: false },
  { title: '关闭其他', key: 'closeOtherstabs', icon: 'icon-close' },
  { title: '关闭左侧', key: 'closeLefttabs', icon: 'icon-to-left' },
  { title: '关闭右侧', key: 'closeRighttabs', icon: 'icon-to-right' },
  { title: '全部关闭', key: 'closeAlltabs', icon: 'icon-close-circle' }
])

// 获取全局属性
const { proxy } = getCurrentInstance()
const tabviewStore = useTabviewStore()
const useRoutes = useRoute()
const $router = useRouter()
const state = reactive({
  tabActive: '',
  affixtabs: []
})
// 缓存的路由
const visitedRoutes = computed(() => tabviewStore.visitedRoutes)
const { tabActive } = toRefs(state)

/**
 * 是否为一直存在的路由，如“首页”这类
 */
const isAffix = (tag) => {
  return tag.meta && tag.meta.affix
}

/**
 * 选中判断
 */
const isActive = (route) => {
  return route.path === useRoutes.path
}

/**
 * 过滤affix状态的tab
 */
const filterAffixtabs = (menus = []) => {
  let tabs = []
  menus.forEach((route) => {
    if (route.meta?.affix) {
      tabs.push({
        fullPath: route.path,
        path: route.path,
        title: route.title,
        meta: { ...route.meta }
      })
    }
    if (route.children) {
      const temptabs = filterAffixtabs(route.children)
      if (temptabs.length >= 1) {
        tabs = [...tabs, ...temptabs]
      }
    }
  })
  return tabs
}

/**
 * 初始化加载时-初始化tab
 */
const initTabs = () => {
  const affixtabItem = (state.affixtabs = filterAffixtabs(props.menuList))
  for (const tab of affixtabItem) {
    tabviewStore.addVisitedRoute(tab)
  }
}

/**
 * 初始化加载时-添加tab
 */
const addTabs = () => {
  const { name } = useRoutes
  if (name) {
    tabviewStore.addVisitedRoute(useRoutes)
  }
  return false
}

/**
 * 关闭tab后，自动跳转到最后一级
 */
const toLastTag = (route) => {
  const latestView = route.slice(-1)[0]
  if (latestView) {
    $router.push({
      path: latestView.path,
      query: latestView.query
    })
  } else {
    $router.push('/')
  }
}

/**
 * 跳转至指定页面
 */
const toThisTag = () => {
  const view = visitedRoutes.value.find((f) => f.path === useRoutes.path)
  if (useRoutes.path !== view?.path) {
    $router.push(view)
  }
  return view
}

/**
 * 点击tabs.pane，切换页面回调
 */
const handleTabClick = (tab) => {
  const route = visitedRoutes.value.find((f) => tab == f.path)
  if (useRoutes.path !== route?.path) {
    $router.push({
      path: route.path,
      query: route.query,
      fullPath: route.fullPath
    })
  } else {
    return false
  }
}

/**
 * 关闭tab
 */
const handleTabRemove = async (tab) => {
  let view
  visitedRoutes.value.forEach((item) => {
    if (tab == item.path) {
      view = item
    }
  })

  await tabviewStore.delVisitedRoute(view)
  if (isActive(view)) {
    toLastTag(visitedRoutes.value)
  }
}

/**
 * 点击菜单功能
 */
const handleCommand = (key) => {
  switch (key) {
    case 'refreshRoute':
      refreshRoute()
      break
    case 'closeOtherstabs':
      closeOtherstabs()
      break
    case 'closeLefttabs':
      closeLefttabs()
      break
    case 'closeRighttabs':
      closeRighttabs()
      break
    case 'closeAlltabs':
      closeAlltabs()
      break
  }
}

// =======================
// ----  tab功能菜单  -----
// =======================
/**
 * 刷新当前页
 * eventBus
 */
const refreshRoute = () => {
  proxy.$eventBus.emit('reload-router-view')
}

/**
 * 关闭其他
 */
const closeOtherstabs = async () => {
  const view = await toThisTag()
  await tabviewStore.delOthersVisitedRoute(view)
}

/**
 * 关闭左侧
 */
const closeLefttabs = async () => {
  const view = await toThisTag()
  await tabviewStore.delLeftVisitedRoute(view)
}

/**
 * 关闭右侧
 */
const closeRighttabs = async () => {
  const view = await toThisTag()
  await tabviewStore.delRightVisitedRoute(view)
}

/**
 * 关闭全部
 */
const closeAlltabs = async () => {
  const view = await toThisTag()
  await tabviewStore.delAllVisitedRoutes()
  if (state.affixtabs.some((tag) => tag.path === view.path)) {
    return
  }
  toLastTag(visitedRoutes.value)
}

/**
 * 监控路由，初始化、更新tabview
 */
watch(
  useRoutes,
  (routes) => {
    let activeStr = ''
    initTabs()
    addTabs()

    visitedRoutes.value.forEach((item) => {
      if (item.path === (routes.meta && routes.meta.highlight)) {
        activeStr = item.path
      } else if (item.path === routes.path) {
        activeStr = (routes.meta && routes.meta.highlight) || item.path
      }
    })
    tabActive.value = activeStr
  },
  { immediate: true }
)
</script>
